package com.loveshes.controller;

import com.loveshes.AsyncOrderFacade;
import com.loveshes.constants.Constants;
import com.loveshes.dto.OrderInfo;
import com.loveshes.util.SleepUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author wangz4
 * @date 2024/12/26 17:48
 */
@RestController
@RequestMapping("order")
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @DubboReference
    private AsyncOrderFacade asyncOrderFacade;
    
    @RequestMapping("queryOrderByIdSync")
    public OrderInfo queryOrderByIdSync(String id) {
        long start = System.currentTimeMillis();
        OrderInfo orderInfo = asyncOrderFacade.queryOrderByIdSync(id);
        logger.error("同步查询 traceId={} 耗时 {}秒",
                RpcContext.getClientAttachment().getAttachment(Constants.MDC_KEY_TRACE_ID), (System.currentTimeMillis() - start) / 1000);
        return orderInfo;
    }
    
    @RequestMapping("queryOrderByIdAsync")
    public OrderInfo queryOrderByIdAsync(String id) {
        long start = System.currentTimeMillis();
        OrderInfo orderInfo = asyncOrderFacade.queryOrderByIdAsync(id);
        logger.error("异步查询 traceId={} 耗时 {}秒",
                RpcContext.getClientAttachment().getAttachment(Constants.MDC_KEY_TRACE_ID), (System.currentTimeMillis() - start) / 1000);
        return orderInfo;
    }
    
    @RequestMapping("queryOrderByIdFuture")
    public OrderInfo queryOrderByIdFuture(String id) {
        long start = System.currentTimeMillis();
        CompletableFuture<OrderInfo> future = asyncOrderFacade.queryOrderByIdFuture(id);
        SleepUtil.sleep(2000L);
        OrderInfo orderInfo = null;
        try {
            orderInfo = future.get(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("异步查询 异常", e);
        }
        logger.error("异步查询 traceId={} 耗时 {}秒",
                RpcContext.getClientAttachment().getAttachment(Constants.MDC_KEY_TRACE_ID), (System.currentTimeMillis() - start) / 1000);
        return orderInfo;
    }
    
}
